jpackage('twc.homephone.verify', function(){
    var imgHost = 'https://registration.timewarnercable.com/images/billImages/';
    function createCustomerImage(div){
        var promise = $.Deferred();

        var img = new Image;
        var src1 = imgHost + div.split('.').pop() +'_Customer_Code.jpg';
        var src2 = imgHost + div +'_Customer_Code.jpg';

        $(img).on({
            load: $.proxy(promise.resolve, img),

            error: function(){
                if (this.src == src2)
                    return promise.reject(this);

                this.src = src2;
            }
        });

        // set first src
        img.src = src1;

        return promise;
    }

    var VerifyModel = Backbone.Model.extend({
        url: twc.routes.get('homephone/cpni/verify')
    });

    this.ChoicesCollection = Backbone.Collection.extend({
        url: twc.routes.get('homephone/cpni/choices'),
        model: Backbone.Model.extend({
            idAttribute: 'value',

            text:function(){
                var key = this.id.split('.').pop();

                return {
                    'customerCode': 'Customer Code',
                    'creditCard': 'Last 4 digits of Credit Card',
                    'eft': 'Last 4 digits of Bank Account'
                }[key];
            }
        }),

        parse:function(response, options){
            return _.map(response, function(choice){
                return { value: choice };
            });
        }
    });

    this.SelectionView = Backbone.View.extend({
        model: VerifyModel,
        el: '#verify-account-modal',

        initialize:function(){
            this.collection.on('reset', this.render, this);
            this.collection.on('error', this.hide, this);

            this.collection.on('fetch', this.onLoading, this);
            this.collection.on('error reset', this.onAlways, this);
        },


        render:function(){
            this.select = this.$el.find('select');
            this.input = this.$el.find('input').fadeIn();

            if (this.collection.length < 2){
                var label = $('<label>', {
                    text: this.collection.first().text()
                });

                this.select.hide()
                this.select.after(label);
            }

            this.collection.each(function(chc){
                var opt = $('<option>', {
                    value: chc.get('value'), text: chc.text()
                });

                this.append(opt);
            }, this.select);

            this.setCustomerCodeImage();

            return this;
        },

        setCustomerCodeImage:function(){
            var self = this;
            var div = this.$el.data('divId');

            if (div){
                createCustomerImage(div).done(function(){
                    self.image = $(this);
                    self.select.trigger('change');

                    $('#verification-instruction').html(self.image);
                });
            }
        },

        hide:function(){
            this.$el.modal('hide');

            return this;
        },

        complete:function(){
            var tmpl = twc.utils.template('verify-complete-template');

            this.$el.html(tmpl()).find('button').on({
                click: function(){
                    window.location.reload();
                    return false;
                }
            });
        },

        verifyError:function(){
            var tmpl = twc.utils.template('data-error');
            var opts = { message: twc.copy.get('cpni/error') };

            $(tmpl(opts)).addClass('span5').insertBefore('#verify-select-method');
        },

        onLoading:function(){
            twc.utils.setLoader(this.$el);
        },

        onAlways:function(){
            this.$el.find('select').prop('disabled', false);
            twc.utils.clearLoader(this.$el);
        },

        onChange:function(e){
            if (this.select.val() == 'cpni.customerCode'){
                this.image.show();
            } else if (this.image) {
                this.image.hide();
            }
        },

        onSubmit:function(){
            var input = this.$el.find('input');

            this.$el.find('.alert').remove();

            if (input.parsley('validate')){
                var button = this.$el.find('button');
                var verify = new VerifyModel({
                    method: this.select.val(),
                    value: this.input.val()
                });

                verify.on('sync', this.complete, this);
                verify.on('error', function(model, resp){
                    twc.utils.clearLoader(button);

                    if (resp.stats === 500) this.collection.trigger('error');
                    else this.verifyError();
                }, this);

                twc.utils.setLoader(button);
                verify.save();
            }
        },

        events:{
            'change select': 'onChange',
            'click button': 'onSubmit',

            'keypress input': function(ev){
                if (ev.which == 13) this.onSubmit();
            }
        }
    });
});

$(function(){
    var Verify = twc.homephone.verify;
    var modal = $('#verify-account-modal');

    function renderError(collection, resp){
        var el = $('<div>').insertAfter('#unverified-homephone h2');

        twc.utils.renderRequestError(resp, el);
    }

    modal.one('shown', function(){
        var coll = new Verify.ChoicesCollection();
        var view = new Verify.SelectionView({ collection: coll });

        coll.on('error', renderError);
        coll.fetch({reset:true});
    }).on('shown', function(){
        modal.find('.alert').remove();
        modal.find('input[type="text"]').val(null);
    });
});
